import {
  ActionType,
  ModalForm,
  PageContainer,
  ProForm,
  ProFormText,
  ProFormTextArea,
  ProFormUploadButton,
} from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import {
  delCategoriesDataAPI,
  delCategoriesDatasAPI,
  loadCategoriesDataAPI,
  addCategoriesDataAPI,
  reviseCategoriesDataAPI,
} from '@/services/api/medApi';
import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Popconfirm, Space } from 'antd';
import { useEffect, useRef, useState } from 'react';
import { logoUrl, serverUrl } from '@/utils/tools';

function MedCategory() {
  const [isShow, setIsShow] = useState(false);
  const ref = useRef<ActionType>();
  const [selectData, setSelectData] = useState<any>([]);
  const [myForm] = ProForm.useForm();
  const [currentId, setCurrentId] = useState('');
  useEffect(() => {
    if (!isShow) {
      setCurrentId('');
    }
  }, [isShow]);

  return (
    <PageContainer>
      <ModalForm
        form={myForm}
        title="编辑"
        open={isShow}
        modalProps={{
          onCancel() {
            setIsShow(false);
          },
          //关闭时进行销毁
          destroyOnClose: true,
          //点空白不消失
          maskClosable: true,
        }}
        onFinish={async (values) => {
          console.log(values);
          // eslint-disable-next-line eqeqeq
          console.log(values.image);

          if (!currentId) {
            console.log(values.image[0].response.data);
            await addCategoriesDataAPI({
              ...values,
              image: serverUrl + values.image[0]?.response.data,
            });
          } else {
            console.log(values.image[0].response.data);

            await reviseCategoriesDataAPI(currentId, {
              ...values,
              image: serverUrl + values.image[0]?.response.data,
            });
            console.log(11);
          }

          message.success('提交成功');
          setIsShow(false);
          ref.current!.reload();
          return true;
        }}
      >
        <ProFormText
          width="lg"
          name="name"
          label="类别"
          tooltip="最长为 24 位"
          placeholder="请输入类别"
        />
        <ProFormUploadButton
          name="image"
          label="图片上传"
          max={1}
          rules={[{ required: false }]}
          fieldProps={{
            name: 'file',
            listType: 'picture-card',
          }}
          action={serverUrl + '/common/upload'}
        />
        <ProFormTextArea name="desc" label="描述详情" placeholder="请输入详情" />
      </ModalForm>

      <ProTable
        actionRef={ref}
        rowKey="id"
        request={loadCategoriesDataAPI}
        columns={[
          {
            title: '序列',
            hideInSearch: true,
            width: '80px',
            render(c, r, i) {
              return i + 1;
            },
          },
          {
            title: '类别',
            dataIndex: 'name',
          },
          {
            title: '图片',
            dataIndex: 'image',
            hideInSearch: true,
            render(c, r) {
              if (r.image && typeof r.image === 'string') {
                console.log(1222);

                r.image = [
                  {
                    uid: crypto.randomUUID(),
                    name: r.name + '.png',
                    thumbUrl: r.image,
                  },
                ];
              }
              console.log(r.image);
              // eslint-disable-next-line eqeqeq
              if (!r.image) {
                console.log(99);
                r.image = [
                  {
                    uid: crypto.randomUUID(),
                    name: r.name + '.png',
                    thumbUrl: logoUrl,
                  },
                ];
              }
              return <img src={r.image[0].thumbUrl} alt="" style={{ maxWidth: '100px' }} />;
            },
          },
          {
            title: '分类描述',
            dataIndex: 'desc',
            hideInSearch: true,
          },
          {
            title: '操作',
            hideInSearch: true,
            render: (text: any) => [
              <Space key="4">
                {/* 修改操作 */}
                <Button
                  key="1"
                  type="primary"
                  onClick={() => {
                    setIsShow(true);
                    myForm.setFieldsValue(text);
                    setCurrentId(text.id);
                  }}
                >
                  修改
                </Button>
                <Popconfirm
                  title="请确认删除"
                  onConfirm={async () => {
                    await delCategoriesDataAPI(text.id);
                    ref.current?.reload();
                  }}
                >
                  <Button key="2" type="primary" danger>
                    删除
                  </Button>
                </Popconfirm>
              </Space>,
            ],
          },
        ]}
        //自定义工具栏
        toolBarRender={() => [
          <Button
            onClick={() => setIsShow(true)}
            key="button"
            icon={<PlusOutlined />}
            type="primary"
          >
            新建
          </Button>,

          <Button
            key="DEL"
            type="primary"
            danger
            style={{ display: selectData.length > 0 ? '' : 'none' }}
            onClick={async () => {
              await delCategoriesDatasAPI(selectData.join(','));
              setSelectData([]);
              ref.current?.reload();
            }}
          >
            删除选中
          </Button>,
        ]}
        rowSelection={{
          onChange(selectionRowKeys) {
            setSelectData(() => selectionRowKeys);
            console.log(selectionRowKeys);
          },
        }}
      ></ProTable>
    </PageContainer>
  );
}

export default MedCategory;
